<template>
  <div class="song-audio">
    <!-- 音频播放器（隐藏） -->
    <audio
      ref="audioPlayer"
      :src="currentSong.url"
      preload="auto"
      @play="onPlay"
      @pause="onPause"
      @ended="onEnded"
      @timeupdate="onTimeUpdate"
      @loadedmetadata="onLoadedMetadata"
    ></audio>

    <!-- 播放控制栏 -->
    <div class="player-container" v-if="currentSong.id">
      <!-- 歌曲信息 -->
      <div class="song-info">
        <div class="song-image" @click="navigateToSongPage">
          <img :src="currentSong.picUrl || defaultImage" :alt="currentSong.name">
          <div class="play-overlay" v-if="!isPlaying">
            <el-icon class="play-icon"><VideoPlay /></el-icon>
          </div>
          <div class="pause-overlay" v-else>
            <el-icon class="pause-icon"><VideoPause /></el-icon>
          </div>
        </div>
        <div class="song-details">
          <div class="song-name">{{ currentSong.name }}</div>
          <div class="singer-name">{{ currentSong.singerName }}</div>
        </div>
      </div>

      <!-- 歌词区域 -->
      <div
          class="lyrics-container"
          v-if="currentSong.id"
          @click="navigateToSongPage">
        <div class="lyrics-content" ref="lyricsContainer">
          <div
              v-for="(line, index) in lyrics"
              :key="index"
              class="lyric-line"
              :class="{ active: index === currentLyricIndex }">
            {{ line.text }}
          </div>
        </div>
      </div>

      <!-- 播放控制按钮 -->
      <div class="control-buttons">
        <el-button
        circle
        @click="changePlayMode"
        >
          <el-icon>
            <component :is="getPlayModeIcon()" />
          </el-icon>
        </el-button>

        <el-button
          circle
          @click="playPrev"
        >
          <el-icon><CaretLeft /></el-icon>
        </el-button>

        <el-button
          circle
          @click="togglePlay"
        >
        <el-icon v-if="isPlaying"><VideoPause /></el-icon>
        <el-icon v-else><VideoPlay /></el-icon>
        </el-button>
        <el-button
          circle
          @click="playNext"
        >
          <el-icon><CaretRight /></el-icon>
        </el-button>
      </div>

      <!-- 进度条 -->
      <div class="progress-container">
        <span class="time">{{ formatTime(currentTime) }}</span>
        <el-slider
          v-model="sliderValue"
          :max="duration"
          @change="onSliderChange"
          class="progress-slider"
        />
        <span class="time">{{ formatTime(duration) }}</span>
      </div>

      <!-- 音量控制和播放列表 -->
      <div class="volume-control">
        <el-icon><headset /></el-icon>
        <el-slider
          v-model="volume"
          :max="1"
          :step="0.01"
          @change="onVolumeChange"
          class="volume-slider"
        />
        <!-- 播放列表按钮 -->
        <el-button
          circle
          @click="togglePlaylist"
          class="playlist-button"
          >
          <el-icon><Menu /></el-icon>
        </el-button>
      </div>
    </div>



    <el-drawer
      v-model="playlistVisible"
      title="播放列表"
      direction="rtl"
      size="300px"
      >
      <div class="playlist-container">
        <div class="playlist-header">
          <span>{{ playlist.length }} 首歌曲</span>
          <el-button
            type="primary"
            link
            @click="clearPlaylist"
            >
            清空列表
          </el-button>
        </div>

        <div class="playlist-items">
          <div
            v-for="(song, index) in playlist"
            :key="song.id"
            class="playlist-item"
            :class="{ active: song.id === currentSong.id }"
            @click="playSong(song)"
            >
            <div class="song-info">
              <div class="song-name">{{ song.name }}</div>
              <div class="singer-name">{{ song.singerName }}</div>
            </div>
            <div class="song-actions">
              <el-button
                type="danger"
                link
                @click.stop="removeFromPlaylist(song.id)"
                >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick} from 'vue'
import {
  VideoPlay,
  VideoPause,
  RefreshLeft,
  RefreshRight,
  Headset,
  Menu,
  Delete,
  CaretLeft,
  CaretRight,
  WindPower,
  Refresh
} from '@element-plus/icons-vue'
import songDefaultImage from '@/assets/img/song-default.png'
import {useRouter} from 'vue-router'
import {usePlayerStore} from "@/store/player";

export default {
  name: 'SongAudio',
  components: {
    VideoPlay,
    VideoPause,
    RefreshLeft,
    RefreshRight,
    Headset,
    Menu,
    Delete,
    CaretLeft,
    CaretRight,
    WindPower,
    Refresh
  },
  props: {
    // 当前播放的歌曲信息
    song: {
      type: Object,
      default: () => ({
        id: null,
        name: '',
        singerName: '',
        url: '',
        picUrl: ''
      })
    }
  },
  setup(props) {
    // 音频元素引用
    const audioPlayer = ref(null)

    // 播放器状态管理
    const playerStore = usePlayerStore()

    // 路由实例
    const router = useRouter()

    // 播放状态
    const isPlaying = ref(false)

    // 当前播放时间
    const currentTime = ref(0)

    // 总时长
    const duration = ref(0)

    // 音量控制（0-1）
    const volume = ref(0.7)

    // 滑块值（用于进度条）
    const sliderValue = ref(0)

    // 默认图片
    const defaultImage = songDefaultImage

    // 歌词容器
    const lyricsContainer = ref(null)
    // 歌词数据
    const lyrics = ref([])
    // 当前歌词索引
    const currentLyricIndex = ref(-1)

    // 播放列表可见性，默认关闭
    const playlistVisible = ref(false)

    // 当前歌曲信息
    const currentSong = computed(() => playerStore.getCurrentSong)

    // 播放列表
    const playlist = computed(() => playerStore.getPlaylist)

    // 播放模式
    const playMode = computed(() => playerStore.getPlayMode)

    // 获取播放模式图标
    const getPlayModeIcon = () => {
      switch (playMode.value) {
        case 'sequence':
          return 'RefreshRight'
        case 'random':
          return 'WindPower'
        case 'single':
          return 'Refresh'
        default:
          return 'RefreshRight'
      }
    }

    /**
     * 跳转到歌曲播放页面
     */
    const navigateToSongPage = () => {
      if (currentSong.value.id) {
        router.push(`/song/${currentSong.value.id}`)
      }
    }

    /**
     * 解析歌词
     * @param {string} lyricText - 歌词文本
     * @returns {Array} 解析后的歌词数组
     */
    const parseLyrics = (lyricText) => {
      if (!lyricText || typeof lyricText !== 'string') {
        console.log(lyricText)
        return []
      }

      console.log(lyricText)

      const lines = lyricText.split('\n')
      const parsedLyrics = []

      for (const line of lines) {
        // 跳过空行
        if (!line.trim()) continue

        // 匹配时间戳格式 [mm:ss.xx] 或 [mm:ss]
        const timeMatches = [...line.matchAll(/\[(\d{2}):(\d{2})(?:\.(\d{2,3}))?\]/g)]

        // 提取歌词文本（去掉所有时间戳）
        const text = line.replace(/\[\d{2}:\d{2}(?:\.\d{2,3})?\]/g, '').trim()

        // 如果没有文本内容，跳过这一行
        if (!text) continue

        // 处理可能包含多个时间戳的行（如歌词重复）
        if (timeMatches.length > 0) {
          for (const match of timeMatches) {
            const minutes = parseInt(match[1])
            const seconds = parseInt(match[2])
            // 处理毫秒部分，确保是正确的数值
            const milliseconds = match[3] ? parseInt(match[3].padEnd(3, '0').substring(0, 3)) : 0
            const time = minutes * 60 + seconds + milliseconds / 1000

            parsedLyrics.push({
              time: time,
              text: text
            })
          }
        } else {
          parsedLyrics.push({
            time: 0,
            text: text
          })
        }
      }

      // 按时间排序
      parsedLyrics.sort((a, b) => a.time - b.time)

      console.log("Parsed lyrics:", parsedLyrics)
      return parsedLyrics
    }

    /**
     * 更新当前歌词索引
     */
    const updateCurrentLyric = () => {
      if (lyrics.value.length === 0) return

      // 查找当前时间对应的歌词
      let newIndex = -1
      for (let i = 0; i < lyrics.value.length; i++) {
        // 如果是最后一行歌词，或者下一歌词的时间大于当前时间
        if (i === lyrics.value.length - 1 || lyrics.value[i + 1].time > currentTime.value) {
          newIndex = i
          break
        }
      }

      // 只有在索引改变时才更新
      if (currentLyricIndex.value !== newIndex) {
        currentLyricIndex.value = newIndex
        // 滚动到当前歌词
        scrollToCurrentLyric()
      }
    }

    /**
     * 滚动到当前歌词
     */
    const scrollToCurrentLyric = () => {
      nextTick(() => {
        if (lyricsContainer.value && currentLyricIndex.value >= 0) {
          const lyricLines = lyricsContainer.value.querySelectorAll('.lyric-line')
          if (lyricLines[currentLyricIndex.value]) {
            lyricLines[currentLyricIndex.value].scrollIntoView({
              behavior: 'smooth',
              block: 'center'
            })
          }
        }
      })
    }

    // 切换播放模式
    const changePlayMode = () => {
      const modes = ['sequence', 'random', 'single']
      const currentIndex = modes.indexOf(playMode.value)
      const nextMode = modes[(currentIndex + 1) % modes.length]
      playerStore.setPlayMode(nextMode)
    }

    // 监听歌曲变化
    const updateCurrentSong = () => {
      if (props.song && props.song.id) {
        currentSong.id = props.song.id
        currentSong.name = props.song.name || ''
        currentSong.singerName = props.song.singerName || ''
        currentSong.url = props.song.url || ''
        currentSong.picUrl = props.song.picUrl || ''

        // 重置播放状态
        currentTime.value = 0
        sliderValue.value = 0
        isPlaying.value = false

        // 设置音量
        if (audioPlayer.value) {
          audioPlayer.value.volume = volume.value
        }
      }
    }

    // 播放音频
    const play = () => {
      if (audioPlayer.value && currentSong.value.id) {
        audioPlayer.value.play()
            .then(() => {
              isPlaying.value = true
              playerStore.setPlayingStatus(true)
            })
            .catch(error => {
              console.error('播放失败:', error)
            })
      }
    }

    // 暂停音频
    const pause = () => {
      if (audioPlayer.value) {
        audioPlayer.value.pause()
        isPlaying.value = false
        playerStore.setPlayingStatus(false)
      }
    }

    // 切换播放/暂停
    const togglePlay = () => {
      if (!currentSong.value.id) return

      if (isPlaying.value) {
        pause()
      } else {
        play()
      }
    }

    //播放上一首
    const playPrev = () => {
      playerStore.playPrev()
    }

    // 播放下一首
    const playNext = () => {
      playerStore.playNext()
    }

    // 播放指定歌曲
    const playSong = (song) => {
      const songWithLyrics = {
        id: song.songId || song.id,
        name: song.songName || song.name,
        singerName: song.singerName || '',
        url: song.songUrl || song.url,
        picUrl: song.songPic || song.picUrl,
        songLyr: song.songLyr || song.lyrics || ''
      }

      playerStore.setCurrentSong(song)
      play()
    }

    // 从播放列表中移除歌曲
    const removeFromPlaylist = (songId) => {
      playerStore.removeFromPlaylist(songId)
    }

    // 清空播放列表
    const clearPlaylist = () => {
      playerStore.clearPlaylist()
    }

    // 显示播放列表
    const togglePlaylist = () => {
      playlistVisible.value = !playlistVisible.value
    }

    // 格式化时间（秒转为 mm:ss 格式）
    const formatTime = (seconds) => {
      if (isNaN(seconds)) return '00:00'

      const min = Math.floor(seconds / 60)
      const sec = Math.floor(seconds % 60)
      return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`
    }

    // 进度条变化处理
    const onSliderChange = (value) => {
      if (audioPlayer.value) {
        audioPlayer.value.currentTime = value
        currentTime.value = value
        playerStore.setCurrentTime(value)
      }
    }

    // 音量变化处理
    const onVolumeChange = (value) => {
      if (audioPlayer.value) {
        audioPlayer.value.volume = value
        playerStore.setVolume(value)
      }
    }

    // 音频播放事件
    const onPlay = () => {
      isPlaying.value = true
      playerStore.setPlayingStatus(true)
    }

    // 音频暂停事件
    const onPause = () => {
      isPlaying.value = false
      playerStore.setPlayingStatus(false)
    }

    // 音频播放结束事件
    const onEnded = () => {
      isPlaying.value = false
      playerStore.setPlayingStatus(false)

      // 根据播放模式决定下一步操作
      switch (playMode.value) {
        case 'single':
          // 单曲循环，重新播放当前歌曲
          play()
          break
        default:
          // 顺序播放或随机播放，播放下一首
          playNext()
      }
    }

      // 时间更新事件
    const onTimeUpdate = () => {
      if (audioPlayer.value) {
        currentTime.value = audioPlayer.value.currentTime
        sliderValue.value = audioPlayer.value.currentTime
        playerStore.setCurrentTime(audioPlayer.value.currentTime)

        console.log('Current time:', currentTime.value)

        // 更新当前歌词
        updateCurrentLyric()
      }
    }

      // 音频元数据加载完成事件
      const onLoadedMetadata = () => {
        if (audioPlayer.value) {
          duration.value = audioPlayer.value.duration || 0
        }
      }

    // 监听当前歌曲变化
    watch(currentSong, (newSong) => {
      if (newSong.id) {
        // 解析歌词 - 修复逻辑
        let lyricText = ''
        // 检查多个可能的歌词字段
        if (newSong.songLyr) {
          lyricText = newSong.songLyr
        } else if (newSong.lyrics) {
          lyricText = newSong.lyrics
        }

        if (lyricText && typeof lyricText === 'string' && lyricText.trim()) {
          lyrics.value = parseLyrics(lyricText)
          console.log('Parsed lyrics:', lyrics.value)
        } else {
          lyrics.value = []
        }
        currentLyricIndex.value = -1

        // 歌曲变化时重新播放
        if (isPlaying.value) {
          setTimeout(() => {
            play()
          }, 100)
        }
      }
    })

      // 组件挂载时的处理
      onMounted(() => {
        // 设置初始音量
        if (audioPlayer.value) {
          audioPlayer.value.volume = volume.value
        }
      })

      // 组件卸载时的清理
      onUnmounted(() => {
        if (audioPlayer.value) {
          audioPlayer.value.pause()
        }
      })

      // 监听 props.song 的变化
      watch(() => props.song, () => {
        updateCurrentSong()
      }, {deep: true})

      return {
        audioPlayer,
        lyricsContainer,
        isPlaying,
        currentTime,
        duration,
        volume,
        sliderValue,
        currentSong,
        playlist,
        playlistVisible,
        lyrics,
        currentLyricIndex,
        defaultImage,
        togglePlay,
        playPrev,
        playNext,
        playSong,
        removeFromPlaylist,
        clearPlaylist,
        togglePlaylist,
        navigateToSongPage,
        changePlayMode,
        getPlayModeIcon,
        formatTime,
        onSliderChange,
        onVolumeChange,
        onPlay,
        onPause,
        onEnded,
        onTimeUpdate,
        onLoadedMetadata
      }
    }
  }
</script>

<style scoped>
.song-audio {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #ffffff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  display: flex;
  flex-direction: column;
}

.player-container {
  display: flex;
  align-items: center;
  height: 80px;
  padding: 0 20px;
}

.song-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.song-image {
  position: relative;
  width: 60px;
  height: 60px;
  border-radius: 5px;
  overflow: hidden;
  cursor: pointer;
  margin-right: 15px;
}

.song-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.play-overlay,
.pause-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.song-image:hover .play-overlay,
.song-image:hover .pause-overlay {
  opacity: 1;
}

.play-icon,
.pause-icon {
  color: white;
  font-size: 24px;
}

.song-details {
  flex: 1;
  min-width: 0;
}

.song-name {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.singer-name {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.control-buttons {
  display: flex;
  align-items: center;
  margin: 0 20px;
}

.control-buttons .el-button {
  margin: 0 5px;
}

.progress-container {
  display: flex;
  align-items: center;
  flex: 2;
  margin: 0 20px;
}

.progress-container .time {
  font-size: 12px;
  color: #666;
  width: 40px;
  text-align: center;
}

.progress-slider {
  flex: 1;
  margin: 0 10px;
}

.progress-slider :deep(.el-slider__runway) {
  height: 3px;
}

.progress-slider :deep(.el-slider__bar) {
  height: 3px;
}

.volume-control {
  display: flex;
  align-items: center;
  width: 200px;
}

.volume-control .el-icon {
  margin-right: 10px;
  color: #666;
}

.volume-slider {
  flex: 1;
  margin-right: 10px;
}

.volume-slider :deep(.el-slider__runway) {
  height: 3px;
}

.volume-slider :deep(.el-slider__bar) {
  height: 3px;
}

.playlist-button {
  margin-left: 10px;
}

/* 歌词展示区域 */
.lyrics-container {
  height: 60px;
  background: white;
  border-top: 1px solid #eee;
  cursor: pointer;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lyrics-content {
  max-width: 800px;
  height: 60px;
  width: 100%;
  text-align: center;
  padding: 0 20px;
  overflow: hidden;
  position: relative;
}

.lyric-line {
  font-size: 14px;
  color: #666;
  padding: 5px 0;
  transition: all 0.3s;
  opacity: 0.6;
}

.lyric-line.active {
  color: #409eff;
  font-weight: 500;
  font-size: 16px;
  opacity: 1;
}

/* 播放列表样式 */
.playlist-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.playlist-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #eee;
}

.playlist-items {
  flex: 1;
  overflow-y: auto;
  padding: 10px 0;
}

.playlist-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.playlist-item:hover {
  background-color: #f5f5f5;
}

.playlist-item.active {
  background-color: #ecf5ff;
}

.playlist-item .song-info {
  flex: 1;
  min-width: 0;
  margin-right: 10px;
}

.playlist-item .song-name {
  font-size: 14px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-item .singer-name {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.playlist-item .song-actions {
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .player-container {
    height: 60px;
  }

  .song-image {
    width: 40px;
    height: 40px;
  }

  .song-name {
    font-size: 12px;
  }

  .singer-name {
    font-size: 10px;
  }

  .control-buttons {
    margin: 0 10px;
  }

  .progress-container {
    margin: 0 10px;
  }

  .volume-control {
    width: 150px;
  }

  .lyrics-container {
    height: 40px;
  }

  .lyric-line {
    font-size: 12px;
  }

  .lyric-line.active {
    font-size: 14px;
  }
}
</style>
